import { useMutation, useQuery } from '@tanstack/react-query';
import { Form, message, Modal, Radio, Space } from 'antd';
import React, { useEffect } from 'react';

import api from '@/apis/api';
import { Logger } from '@/components/useLogger';
import localINFO from '@/utils/localInfo';

import styles from '../styles.module.less';

type LogSetModalProps = {
  visible: boolean;
  setVisible: (visible: boolean) => void;
};

const LogSetModal: React.FC<LogSetModalProps> = ({ visible, setVisible }) => {
  const [form] = Form.useForm();

  const { data: loglevel } = useQuery({
    queryKey: ['getLogLevel'],
    queryFn: async () => {
      const res: any = await api.GetLogLevel();
      return res.data;
    },
    enabled: !!visible,
  });

  useEffect(() => {
    if (loglevel && visible) {
      form.setFieldsValue({ logLevel: loglevel?.log_class });
    }
  }, [loglevel, form, visible]);

  const SetLogLevel = useMutation({
    mutationFn: async (params: any) => api.SetLogLevel(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('设置成功');
      } else {
        message.error(`设置失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('设置失败');
    },
  });

  const handleOk = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    await SetLogLevel.mutateAsync({
      log_class: values.logLevel,
    });
    form.resetFields();
    setVisible(false); // 关闭弹窗
  };

  const onHandleCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <>
      <Modal
        title="设置操作日志等级"
        open={visible}
        onOk={handleOk}
        onCancel={onHandleCancel}
        cancelText="取消"
        okText="确定"
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form form={form}>
          <div style={{ marginLeft: 4 }}>
            <p>请选择你想要设置的固件日志等级：</p>
            <Form.Item className={styles.FormItem} name="logLevel">
              <Radio.Group>
                <Space direction="vertical">
                  <Radio value={0}>完全记录</Radio>
                  <Radio value={1}>错误记录</Radio>
                </Space>
              </Radio.Group>
            </Form.Item>
          </div>
        </Form>
      </Modal>
    </>
  );
};

export default React.memo(LogSetModal);
